package com.qf.ability.gateway.security.exception;

import com.qf.common.core.base.Codes;
import com.qf.common.core.base.R;
import com.qf.common.core.base.RetUtils;
import com.qf.common.core.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

@Component
@Slf4j
public class AuthenticationFailException implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {

        log.error("[Authentication-Error] - 认证异常！", exception);

        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();

        //统一处理认证失败的异常
        R result = RetUtils.create(Codes.AUTH_ERROR, null);
        //将该对象转换成JSON
        String resultJson = JsonUtils.obj2json(result);

        DataBuffer dataBuffer = null;
        try {
            dataBuffer = response.bufferFactory().wrap(resultJson.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //处理响应头
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");

        return response.writeWith(Mono.just(dataBuffer));
    }
}
